package com.hontech.libratest.activity.fragment.sub

import android.view.View
import android.widget.Button
import android.widget.EditText
import com.hontech.libratest.R
import com.hontech.libratest.activity.window.showProg
import com.hontech.libratest.conn.Device
import com.hontech.libratest.conn.cargoCheck
import com.hontech.libratest.conn.cargoReset
import com.hontech.libratest.conn.cargoTest
import com.hontech.libratest.utils.onClick
import com.hontech.libratest.utils.toInt

class CargoTest (view: View) {

    private val cargoTest = view.findViewById<Button>(R.id.id_main_btn_cargo_test)
    private val cargoCheck = view.findViewById<Button>(R.id.id_main_btn_cargo_check)
    private val cargoReset = view.findViewById<Button>(R.id.id_main_btn_cargo_reset)
    private val cargoResetAll = view.findViewById<Button>(R.id.id_main_btn_cargo_reset_all)

    private val etRow = view.findViewById<EditText>(R.id.id_main_et_row)
    private val etCol = view.findViewById<EditText>(R.id.id_main_et_col)
    private val etSize = view.findViewById<EditText>(R.id.id_main_et_size)

    init {
        cargoTest.onClick(::onClickTest)
        cargoCheck.onClick(::onClickCheck)
        cargoReset.onClick(::onClickReset)
        cargoResetAll.onClick(::onClickResetAll)
    }

    private suspend fun onClickResetAll() {
        val row = etRow.toInt()
        val w = showProg(cargoCheck, "正行复位")
        try {
            for (col in 1..10) {
                w.show(cargoCheck, "正在复位:${row}-${col}")
                cargoReset(row, col)
            }
            w.success("第${row}行复位成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onClickTest() {
        val row = etRow.toInt()
        val col = etCol.toInt()
        val size = etSize.toInt()
        val w = showProg(etCol, "货道测试")

        try {
            cargoTest(row, col, size)
            w.success("货道测试成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onClickCheck() {
        val row = etRow.toInt()
        val col = etCol.toInt()
        val w = showProg(etCol, "货道检测")

        try {
            cargoCheck(row, col)
            w.success("货道检测成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onClickReset() {
        val row = etRow.toInt()
        val col = etCol.toInt()
        val w = showProg(etCol, "货道复位")

        try {
            cargoReset(row, col)
            w.success("货道复位成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }
}